module.exports = app => {
    const express = require("express")
    const router = express.Router({
        //合并url参数，使其能被req.params访问到
        mergeParams: true
    })
    const AdminUser = require('../../model/adminUser')
    const jwt = require("jsonwebtoken")
    const {
        secret
    } = require("../../config/key")


    //登录校验中间件
    const authMiddleware = require('../../middleware/auth')


    //资源模型中间件
    const resourceMiddleware = require('../../middleware/resource')

    //创建资源
    router.post("/create", async (req, res) => {
        //判断歌曲是否存在\
        let val = ""
        if (req.Model.modelName === "AdminUser") {
            val = await req.Model.findOne({
                username: req.body.username
            })
        } else {
            val = await req.Model.findOne({
                m_id: req.body.m_id
            })
        }
        if (val) {
            return res.status(409).send(`该${req.params.resource}已存在`)
        }
        const newSong = await new req.Model(req.body).save()
        res.send(newSong)
    })
    //资源列表
    router.get("/list", async (req, res) => {
        const queryOptions = {}
        if (req.Model.modelName === 'MusicList') {
            queryOptions.populate = 'musics'
        }
        const Model = require(`../../model/${req.params.resource}`)
        let {
            current,
            size
        } = req.query
        let cur = parseInt(current) - 1
        let siz = parseInt(size)
        const count = await Model.find().setOptions(queryOptions).countDocuments()
        const items = await Model.find().setOptions(queryOptions).limit(siz).skip(cur * siz)
        res.send({
            items,
            count
        })
    })
    //资源详情
    router.get("/edit/:id", async (req, res) => {
        const model = await req.Model.findById(req.params.id)
        res.send(model)
    })
    //修改资源
    router.put("/edit/:id", async (req, res) => {
        //    delete req.body.rl_di
        //    delete req.body.url_di{overwrite:true}
        const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
        res.send(model)
    })
    //删除资源
    router.delete("/delete/:id", async (req, res) => {
        await req.Model.findByIdAndDelete(req.params.id, req.body)
        res.send({
            success: true
        })
    })


    app.use('/admin/rest/:resource', authMiddleware(), resourceMiddleware(), router)

    app.post('/admin/login', async (req, res) => {
        const {
            username,
            password
        } = req.body
        //根据用户名找用户
        //select将密码一起取出来
        const user = await AdminUser.findOne({
            username
        }).select('+password')
        if (!user) {
            return res.status(422).send({
                message: '用户不存在'
            })
        }
        //校验密码
        const isValid = require('bcryptjs').compareSync(password, user.password)
        if (!isValid) {
            return res.status(422).send({
                message: '密码错误'
            })
        }
        //返回token
        const token = jwt.sign({
            id: user._id,
        }, secret)
        res.send({
            token
        })
    })
    //错误处理中间件
    app.use(async (err, req, res, next) => {
        res.status(err.statusCode || 500).send({
            message: err.message
        })
    })
}